package com.man.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class SerializationUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 序列化方法，将对象转换为JSON字符串
     *
     * @param object 要序列化的对象
     * @param <T>    泛型类型
     * @return 序列化后的JSON字符串
     * @throws RuntimeException 如果序列化失败
     */
    public static <T> String serialize(T object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to serialize object", e);
        }
    }

    /**
     * 反序列化方法，将JSON字符串转换为指定的泛型对象
     *
     * @param jsonStr JSON字符串
     * @param typeRef 泛型类型引用
     * @param <T>     泛型类型
     * @return 反序列化后的对象
     * @throws RuntimeException 如果反序列化失败
     */
    public static <T> T deserialize(String jsonStr, TypeReference<T> typeRef) {
        try {
            return objectMapper.readValue(jsonStr, typeRef);
        } catch (IOException e) {
            throw new RuntimeException("Failed to deserialize JSON string", e);
        }
    }
}